import { PluginCreator } from 'postcss'

const postcssDemo: PluginCreator<{
  divisor?: number
  multiple?: number
  decimalPlaces?: number
  targetUnits?: string
  include?: string
}> = (options = {}) => {
  // Work with options here
  const opts = {
    divisor: 1,
    multiple: 2,
    decimalPlaces: 2,
    targetUnits: 'px',
    comment: 'no',
    include: 'src',
    ...options
  }

  function replacePx(str: string) {
    if (!str) {
      return ''
    }
    return str.replace(/\b(\d+(\.\d+)?)px\b/gi, (match, x) => {
      const size = (x * opts.multiple) / opts.divisor
      return size % 1 === 0
        ? size + opts.targetUnits
        : size.toFixed(opts.decimalPlaces) + opts.targetUnits
    })
  }

  return {
    postcssPlugin: 'postcss-demo',
    Root(css) {
      // Transform CSS AST here
      // 处理方法 一
      css.walkDecls((decl) => {
        const filePath = css.source?.input.file
        if (!opts.include || (filePath && filePath.indexOf(opts.include)) === -1) {
          return
        }
        const next = decl.next()
        if (decl && next && next?.type === 'comment' && next?.text === opts.comment) {
          next.remove()
        } else {
          decl.value = replacePx(decl.value)
        }
      })
      // 处理方法 二
      // css.walkRules((rule) => {
      //   rule.walkDecls((decl) => {
      //     const next = decl.next()
      //     if (decl && next && next?.type === 'comment' && next?.text === opts.comment) {
      //       next.remove()
      //     } else {
      //       decl.value = replacePx(decl.value)
      //     }
      //   })
      // })
    }
    /*
    Declaration(decl, postcss) {
      // The faster way to find Declaration node
    }
    */
    /*
    Declaration: {
      color: (decl, postcss) {
        // The fastest way find Declaration node if you know property name
      }
    }
    */
  }
}
postcssDemo.postcss = true
export default postcssDemo
